﻿using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using DotNet.Utilities;
using PropertyChanged;
using WindowsAPICodePack.Dialogs;
using WPFTemplate;
using WPFTemplateLib.Controls.WpfToast;

namespace FHBG_WPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    [AddINotifyPropertyChangedInterface]
    public partial class MainWindow : Window
    {
        #region 成员

        /// <summary>
        /// 输入/选取 的字符
        /// </summary>
        private string _punctuation;

        private string _signLeft;
        private string _signRight;
        private string _str;

        /// <summary>
        /// 当前编辑的文件名
        /// </summary>
        private string _fileName = "";

        /// <summary>
        /// 查找与替换中的位置
        /// </summary>
        private int _findPostion = 0;

        /// <summary>
        /// 是否需要保存
        /// </summary>
        private bool _needSave = false;

        public MainWindow()
        {
            InitializeComponent();

            Version = AssemblyHelper.AssemblyVersion;

            CommandBindings.Add(new CommandBinding(ApplicationCommands.New, ExecuteNewCmd));
            CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, ExecuteOpenCmd));
            CommandBindings.Add(new CommandBinding(ApplicationCommands.Save, ExecuteSaveCmd));
            CommandBindings.Add(new CommandBinding(ApplicationCommands.SaveAs, ExecuteSaveAsCmd));
            CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, ExecuteCloseCmd));
        }

        #endregion

        #region 绑定

        public string Version { get; set; }

        #endregion

        #region 事件和命令方法

        /// <summary>
        /// [事件触发] 关于按钮
        /// </summary>
        private void BtnAbout_OnClick(object sender, RoutedEventArgs e)
        {
            new AboutWindow().ShowDialog();
        }

        /// <summary>
        /// [事件触发] 窗口正在关闭
        /// </summary>
        private void MainWindow_OnClosing(object sender, CancelEventArgs e)
        {
            if (!SaveOldFile())
                e.Cancel = true; //不退出，程序继续运行
        }

        /// <summary>
        /// [事件触发] 文本变化
        /// </summary>
        private void TbMain_OnTextChanged(object sender, TextChangedEventArgs e)
        {
            _needSave = true;
        }

        /// <summary>
        /// [执行命令] 新建
        /// </summary>
        private void ExecuteNewCmd(object sender, ExecutedRoutedEventArgs e)
        {
            if (!SaveOldFile())
                return;

            TbMain.Text = "";
            _fileName = "";
            _needSave = false;
        }

        /// <summary>
        /// [执行命令] 打开
        /// </summary>
        private void ExecuteOpenCmd(object sender, ExecutedRoutedEventArgs e)
        {
            if (!SaveOldFile())
                return;

            CommonOpenFileDialog dialog = new()
            {
                IsFolderPicker = false,
                AddToMostRecentlyUsedList = true,
                Filters =
                {
                    new CommonFileDialogFilter("文本文件", "txt"),
                    new CommonFileDialogFilter("All", "*")
                },
            };

            using (dialog)
            {
                if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
                {
                    _fileName = dialog.FileName;
                    TbMain.Text = File.ReadAllText(_fileName);
                    _needSave = false;
                    Toast.Show("读取成功");
                }
            }
        }

        /// <summary>
        /// [执行命令] 保存
        /// </summary>
        private void ExecuteSaveCmd(object sender, ExecutedRoutedEventArgs e)
        {
            if (_fileName.Length != 0)
            {
                _needSave = false;
                SaveCurrentFile();
            }
            else
            {
                SaveAsNewFile();
            }
        }

        /// <summary>
        /// [执行命令] 另存为
        /// </summary>
        private void ExecuteSaveAsCmd(object sender, ExecutedRoutedEventArgs e)
        {
            SaveAsNewFile();
        }

        /// <summary>
        /// [执行命令] 退出
        /// </summary>
        private void ExecuteCloseCmd(object sender, ExecutedRoutedEventArgs e)
        {
            if (!SaveOldFile())
                return;

            Close();
        }

        #endregion

        #region 通用方法

        /// <summary>
        /// 保存旧文件
        /// </summary>
        /// <returns>true-用户选择了保存或不保存，false-用户选择了取消</returns>
        public bool SaveOldFile()
        {
            bool result = true;
            if (_needSave)
            {
                var messageBoxResult = MessageBox.Show(this, "要保存当前更改吗？", "保存更改吗？", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
                switch (messageBoxResult)
                {
                    case MessageBoxResult.Yes:
                    {
                        if (_fileName.Length != 0)
                        {
                            SaveCurrentFile();
                        }
                        else
                        {
                            SaveAsNewFile();
                        }

                        _needSave = false;
                        break;
                    }
                    case MessageBoxResult.No:
                    {
                        _needSave = false;
                        break;
                    }
                    case MessageBoxResult.Cancel:
                    {
                        result = false;
                        break;
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 另存为
        /// </summary>
        private void SaveAsNewFile()
        {
            CommonOpenFileDialog dialog = new()
            {
                Title = "另存为",
                IsFolderPicker = false,
                AddToMostRecentlyUsedList = true,
                Filters = 
                { 
                    new CommonFileDialogFilter("文本文件", "txt"),
                    new CommonFileDialogFilter("All", "*")
                },
                //DefaultExtension = "txt", //设置了这个则如果没写后缀会用这个,但是好像就保存不了为其它后缀了。
                DefaultFileName = "New.txt",
            };

            using (dialog)
            {
                if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
                {
                    _fileName = dialog.FileName;
                    SaveCurrentFile();
                    _needSave = false;
                    Toast.Show("另存为成功");
                }
            }
        }

        /// <summary>
        /// 保存当前文件
        /// </summary>
        private void SaveCurrentFile()
        {
            File.WriteAllText(_fileName, TbMain.Text);
            Toast.Show("保存成功");
        }

        #endregion
    }
}
